<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="../css/mui.min.css" rel="stylesheet" />
		<link href="../css/main.css" rel="stylesheet" />
		<link href="../css/mui.imageviewer.css" rel="stylesheet" />
		<style>
			html,
			body {
				height: 100%;
				margin: 0px;
				padding: 0px;
				overflow: hidden;
				-webkit-touch-callout: none;
				-webkit-user-select: none;
			}
			footer {
				position: fixed;
				width: 100%;
				height: 50px;
				min-height: 50px;
				border-top: solid 1px #bbb;
				left: 0px;
				bottom: 0px;
				overflow: hidden;
				padding: 0px 50px;
				background-color: #fafafa;
			}
			.footer-left {
				position: absolute;
				width: 50px;
				height: 50px;
				left: 0px;
				bottom: 0px;
				text-align: center;
				vertical-align: middle;
				line-height: 100%;
				padding: 12px 4px;
			}
			.footer-right {
				position: absolute;
				width: 50px;
				height: 50px;
				right: 0px;
				bottom: 0px;
				text-align: center;
				vertical-align: middle;
				line-height: 100%;
				padding: 12px 5px;
				display: inline-block;
			}
			.footer-center {
				height: 100%;
				padding: 5px 0px;
			}
			.footer-center [class*=input] {
				width: 100%;
				height: 100%;
				border-radius: 5px;
			}
			.footer-center .input-text {
				background: #fff;
				border: solid 1px #ddd;
				padding: 10px !important;
				font-size: 16px !important;
				line-height: 18px !important;
				font-family: verdana !important;
				overflow: hidden;
			}
			.footer-center .input-sound {
				background-color: #eee;
			}
			.mui-content {
				height: 100%;
				padding: 44px 0px 50px 0px;
				overflow: auto;
				background-color: #eaeaea;
			}
			#msg-list {
				height: 100%;
				overflow: auto;
				-webkit-overflow-scrolling: touch;
			}
			.msg-item {
				padding: 8px;
				clear: both;
			}
			.msg-item .mui-item-clear {
				clear: both;
			}
			.msg-item .msg-user {
				width: 38px;
				height: 38px;
				border: solid 1px #d3d3d3;
				display: inline-block;
				background: #fff;
				border-radius: 3px;
				vertical-align: top;
				text-align: center;
				float: left;
				padding: 3px;
				color: #ddd;
			}
			
			.msg-item .msg-user-img{
				width: 38px;
				height: 38px;
				display: inline-block;
				border-radius: 3px;
				vertical-align: top;
				text-align: center;
				float: left;
				color: #ddd;
			}
			
			.msg-item .msg-content {
				display: inline-block;
				border-radius: 5px;
				border: solid 1px #d3d3d3;
				background-color: #FFFFFF;
				color: #333;
				padding: 8px;
				vertical-align: top;
				font-size: 15px;
				position: relative;
				margin: 0px 8px;
				max-width: 75%;
				min-width: 35px;
				float: left;
			}
			.msg-item .msg-content .msg-content-inner {
				overflow-x: hidden;
			}
			.msg-item .msg-content .msg-content-arrow {
				position: absolute;
				border: solid 1px #d3d3d3;
				border-right: none;
				border-top: none;
				background-color: #FFFFFF;
				width: 10px;
				height: 10px;
				left: -5px;
				top: 12px;
				-webkit-transform: rotateZ(45deg);
				transform: rotateZ(45deg);
			}
			.msg-item-self .msg-user,
			.msg-item-self .msg-content {
				float: right;
			}
			.msg-item-self .msg-content .msg-content-arrow {
				left: auto;
				right: -5px;
				-webkit-transform: rotateZ(225deg);
				transform: rotateZ(225deg);
			}
			.msg-item-self .msg-content,
			.msg-item-self .msg-content .msg-content-arrow {
				background-color: #4CD964;
				color: #fff;
				border-color: #2AC845;
			}
			footer .mui-icon {
				color: #000;
			}
			footer .mui-icon:active {
				color: #007AFF !important;
			}
			footer .mui-icon-paperplane:before {
				content: "发送";
			}
			footer .mui-icon-paperplane {
				/*-webkit-transform: rotateZ(45deg);
				transform: rotateZ(45deg);*/
				
				font-size: 16px;
				word-break: keep-all;
				line-height: 100%;
				padding-top: 6px;
				color: rgba(0, 135, 250, 1);
			}
			#msg-sound {
				-webkit-user-select: none !important;
				user-select: none !important;
			}
			.rprogress {
				position: absolute;
				left: 50%;
				top: 50%;
				width: 140px;
				height: 140px;
				margin-left: -70px;
				margin-top: -70px;
				background-image: url(../images/arecord.png);
				background-repeat: no-repeat;
				background-position: center center;
				background-size: 30px 30px;
				background-color: rgba(0, 0, 0, 0.7);
				border-radius: 5px;
				display: none;
				-webkit-transition: .15s;
			}
			.rschedule {
				background-color: rgba(0, 0, 0, 0);
				border: 5px solid rgba(0, 183, 229, 0.9);
				opacity: .9;
				border-left: 5px solid rgba(0, 0, 0, 0);
				border-right: 5px solid rgba(0, 0, 0, 0);
				border-radius: 50px;
				box-shadow: 0 0 15px #2187e7;
				width: 46px;
				height: 46px;
				position: absolute;
				left: 50%;
				top: 50%;
				margin-left: -23px;
				margin-top: -23px;
				-webkit-animation: spin 1s infinite linear;
				animation: spin 1s infinite linear;
			}
			.r-sigh{
				display: none;
				border-radius: 50px;
				box-shadow: 0 0 15px #2187e7;
				width: 46px;
				height: 46px;
				position: absolute;
				left: 50%;
				top: 50%;
				margin-left: -23px;
				margin-top: -23px;
				text-align: center;
				line-height: 46px;
				font-size: 40px;
				font-weight: bold;
				color: #2187e7;
			}
			.rprogress-sigh{
				background-image: none !important;
			}
			.rprogress-sigh .rschedule{
				display: none !important;
			}
			.rprogress-sigh .r-sigh{
				display: block !important;
			}
			.rsalert {
				font-size: 12px;
				color: #bbb;
				text-align: center;
				position: absolute;
				border-radius: 5px;
				width: 130px;
				margin: 5px 5px;
				padding: 5px;
				left: 0px;
				bottom: 0px;
			}
			@-webkit-keyframes spin {
				0% {
					-webkit-transform: rotate(0deg);
				}
				100% {
					-webkit-transform: rotate(360deg);
				}
			}
			@keyframes spin {
				0% {
					transform: rotate(0deg);
				}
				100% {
					transform: rotate(360deg);
				}
			}
			
		
			.cancel {
				background-color: darkred;
			}
			.mui-btn-smail
			{
				    font-size: 12px;
				    padding: 5px 8px;
					
			}
			#send-btn.mui-btn-smail{
				margin-left: -20px;
			}
			.footer-center{
				width: 95%;
			}
			
			.msg-item-friends .msg-content::after{
				content: "";
				position: absolute;
				left: 0;
				transform:rotate(45deg) translateX(-82%);
				width: 10px;
				height: 10px;
				top: 20px;
				
			}
			.msg-item-friends .msg-content,
			.msg-item-friends .msg-content::after{
				background-color: rgba(0, 183, 229, 1);
				border-color: rgba(0, 183, 229, 1);
				color: #FFFFFF;
			}
			
			.msg-item-sys{
				text-align:center;
				font-size: 14px;
				color: #9b9b9e;
			}
			
			.mui-action-back-me{
				color:#fff
			}
			.mui-bar .mui-icon:active{
				color:#fff;
				    opacity: .5;
			}
				
		</style>
	</head>

	<body contextmenu="return false;">
		<header class="mui-bar mui-bar-nav">
			<div class="mui-margin-25"></div>
			<a class="mui-action-back-me mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title" id="page-title"></h1>
		</header>

		<div class="mui-content">
			<div id='msg-list'>

			</div>
		</div>
		<footer>
			<div class="footer-left">
				<i id='msg-image' class="mui-icon mui-icon-camera" style="font-size: 28px;"></i>
			</div>
			<div class="footer-center">
				<textarea id='msg-text' type="text" class='input-text'></textarea>
			</div>
			<label class="footer-right">
				<button type="button" class="mui-btn mui-btn-blue mui-btn-outlined mui-btn-smail" id="send-btn">发送</button>
			</label>
		</footer>

		<script src="../js/mui.min.js"></script>
		<script src="../js/main.js"></script>
		<script src="../js/jquery-3.1.1.min.js"></script>
		<script type="text/javascript" charset="utf-8">
			function dateFormat(fmt, date) {
				let ret;
				const opt = {
					"y+": date.getFullYear().toString(), // 年
					"M+": (date.getMonth() + 1).toString(), // 月
					"d+": date.getDate().toString(), // 日
					"H+": date.getHours().toString(), // 时
					"m+": date.getMinutes().toString(), // 分
					"S+": date.getSeconds().toString() // 秒
					// 有其他格式化字符需求可以继续添加，必须转化成字符串
				};
				for (let k in opt) {
					ret = new RegExp("(" + k + ")").exec(fmt);
					if (ret) {
						fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
					};
				};
				return fmt;
			}
			mui.init({
				gestureConfig: {
					tap: true, //默认为true
					doubletap: true, //默认为false
					longtap: true, //默认为false
					swipe: true, //默认为true
					drag: true, //默认为true
					hold: true, //默认为false，不监听
					release: true //默认为false，不监听
				}
			});
			var msgHistoryManager;
			const CHAT = {
				time: "",
				writeForMe(obj) {
					CHAT.checkAndWriteTimeBox();
					const html = CHAT.getMeHtml(obj);
					$("#msg-list").append(html);
					CHAT.checkAndScollDown()
				},
				writeForFriend(obj) {
					CHAT.checkAndWriteTimeBox();
					const html = CHAT.getFriendHtml(obj);
					$("#msg-list").append(html);
					CHAT.checkAndScollDown()
				},
				writeForSys(obj) {
					const html = CHAT.getSysHtml(obj);
					$("#msg-list").append(html);
					CHAT.checkAndScollDown()
				},
				getMeHtml(obj) {
					var html = "";
					html += '<div class="msg-item msg-item-self">';
					html += '<img class="msg-user-img" style="float:right" src="' + (obj.photo ? obj.photo : "../img/logo.png") +
						'" alt="" />';
					html += '<div class="msg-content">';
					html += '<div class="msg-content-inner">';
					if (obj.content.text && obj.content.text !== "") {
						html += obj.content.text;
					}
					if (obj.content.img && obj.content.img !== "") {
						html += '<img class="msg-content-image" src="' + (obj.content.img ? obj.content.img : "../img/bf02.jpg") +
							'" style="max-width: 100px;" />';
					}
					html += '</div>';
					html += '<div class="msg-content-arrow"></div>';
					html += '</div>';
					html += '</div>';
					return html;
				},
				getFriendHtml(obj) {
					var html = "";
					html += '<div class="msg-item msg-item-friends">';
					html += '<img class="msg-user-img" src="' + (obj.photo ? obj.photo : "../img/logo.png") + '" alt="" />';
					html += '<div class="msg-content">';
					html += '<div class="msg-content-inner">';
					if (obj.content.text && obj.content.text !== "") {
						html += obj.content.text;
					}
					if (obj.content.img && obj.content.img !== "") {
						html += '<img class="msg-content-image" src="' + (obj.content.img ? obj.content.img : "../img/bf02.jpg") +
							'" style="max-width: 100px;" />';
					}
					html += '</div>';
					html += '</div>';
					html += '</div>';
					return html;
				},
				getSysHtml(obj) {
					var html = "";
					html += '<div class="msg-item msg-item-sys">';
					html += obj.time;
					html += '</div>';
					return html;
				},
				robat(content) {
					_SERVER.robat.chat(content).then(res => {
						{
							CHAT.writeForFriend({
								photo: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1578992728140&di=b426032fae5c11e60cf255bad47b9170&imgtype=0&src=http%3A%2F%2Fimg.51miz.com%2FElement%2F00%2F75%2F01%2F69%2F27774472_E750169_2ff36b59.png%2521%2Fquality%2F90%2Funsharp%2Ftrue%2Fcompress%2Ftrue%2Fformat%2Fpng",
								content: {
									text: res.text,
									img: ""
								}
							})
						}

					})
				},
				checkAndScollDown() {
					var div = document.getElementById('msg-list');
					div.scrollTop = div.scrollHeight;

				},
				checkAndWriteTimeBox() {
					var date = dateFormat("yyyy-MM-dd HH:mm", new Date());

					if (CHAT.time !== date) {
						CHAT.time = date;
						let obj = {
							time: CHAT.time
						};
						CHAT.writeForSys(obj)
						msgHistoryManager.pushMsg({
							type: 0,
							entity: obj
						});
					}

				}
			}
			mui.plusReady(function() {

				var entity = JSON.parse(plus.storage.getItem("userInfo"));

				var currentWebview = plus.webview.currentWebview();

				currentWebview.addEventListener("close",function(){
					var chatWebview = plus.webview.getWebviewById("chat");
					chatWebview.evalJS("initSocket()"); 
				})

				const messageManager = new APP.model.MessageManager(entity.id);
				msgHistoryManager = new APP.model.MsgHistoryManager(entity.id, currentWebview._ext_user_id);

				currentWebview.setStyle({
					softinputMode: "adjustResize"
				});

				initCurrentPage(currentWebview);

				const _socket = new Socket("ws://" + _GLOBAL_SERVER_IP + ":8611/ws");
				_socket.onopen = function() {
					// 登录
					_socket.send({
						cmd: 10,
						extAttr: {
							userId: entity.id
						}
					});
				}
				_socket.onmessage = function(e) {
					var _content = e.data;
					_content = JSON.parse(_content);

					const friends = APP.cache.UserFriends.get(entity.id);
					var _friend = null;
					for (var i = 0; i < friends.length; i++) {
						if (friends[i].friendId === currentWebview._ext_user_id) {
							_friend = friends[i];
							break;
						}
					}
					/*
						2种情况
						
						1> 发送消息成功
						2> 好友发来消息
					*/
					if (_EventType.CHAT_SEND == _content.cmd) {
						let msgObj = {
							photo: entity.photoDefault,
							content: {
								text: _content.msgType !== "2" ? _content.content : "",
								img: _content.msgType === "2" ? _content.content : ""
							}
						};
						CHAT.writeForMe(msgObj)
						$("#msg-text").val("");

						msgHistoryManager.pushMsg({
							type: 1,
							entity: msgObj
						});

					} else if (_EventType.CHAT_FRIEND == _content.cmd) {
						let msgObj = {
							photo: currentWebview._ext_user_photo,
							content: {
								text: _content.msgType !== "2" ? _content.content : "",
								img: _content.msgType === "2" ? _content.content : ""
							}
						};
						CHAT.writeForFriend(msgObj)
						msgHistoryManager.pushMsg({
							type: 2,
							entity: msgObj
						});
					}

					setTimeout(() => {
						const fid = _friend.friendId;
						const fphoto = _friend.photo;
						const fname = _friend.friendName;
						const fmsgText = _content.content;
						const isRead = true;
						// 缓存消息列表
						messageManager.pushMsg(new APP.model.Message(fid, fphoto, fname, fmsgText, isRead));
						const chatWebview = plus.webview.getWebviewById("chat");
						chatWebview.evalJS("_initMsgs()");
					}, 0);

				}
				_socket.init();



				mui(".mui-action-back-me")[0].addEventListener("tap",function(){
					var chatWebview = plus.webview.getWebviewById("chat");
					chatWebview.evalJS("initSocket()"); 
					
					mui.back();
					setTimeout(()=>{
						plus.webview.currentWebview().close();
					},600)
				})
				mui("#send-btn")[0].addEventListener("tap", function() {
					var val = $("#msg-text").val();
					if (!val || val === "") {
						return;
					}
					_socket.send({
						cmd: 20,
						content: $("#msg-text").val(),
						sender: entity.id,
						receive: currentWebview._ext_user_id,
					})
				})
				mui("#msg-image")[0].addEventListener("tap", function() {
					plus.nativeUI.actionSheet({
						title: "图片发送",
						cancel: "取消",
						buttons: [{
							title: "拍照"
						}, {
							title: "从系统相册选择"
						}]
					}, function(e) {
						switch (e.index) {
							// 打开相册选择图片上传
							case 1:
								openCamera();
								break;
							case 2:
								openGallery();
								break;
						}
					})
				})

				// 打开相册 
				const openGallery = function() {
					plus.gallery.pick(function(e) {
						// 压缩上传图片
						zipImageAndUpload(e);
					}, function(e) {
						console.log("取消选择图片");
					}, {
						filter: "image",
						multiple: false
					});
				}

				function openCamera() {
					const camera = plus.camera.getCamera(1);
					camera.captureImage(function(e) {
						plus.io.resolveLocalFileSystemURL(e, function(p) {
							console.log(p.fullPath)
							zipImageAndUpload(p.fullPath);
						})
					}, function(err) {}, {
						filename: '_doc/camera/'
					})
				}


				function zipImageAndUpload(path) {
					var wt = plus.nativeUI.showWaiting();
					plus.zip.compressImage({
						src: path,
						quality: 20,
						overwrite: true,
						dst: "_doc/camera/" + path
					}, function(p) {

						var task = plus.uploader.createUpload(_GLOBAL_SERVER_HOST + "/file/upload", {
							method: "post"
						}, function(t, status) {
							if (status == 200) {
								wt.close(); //关闭等待提示按钮
								var res = JSON.parse(t.responseText);
								if (res.code == "200") {
									_socket.send({
										cmd: 20,
										content: res.data.url,
										msgType: 2,
										sender: entity.id,
										receive: currentWebview._ext_user_id
									})
								}
							} else {
								wt.close(); //关闭等待提示按钮
								mui.toast("图片服务器异常")
							}

						});
						task.addFile(p.target, {
							key: "file"
						});
						task.start();
					})
				}

				var imgEl = ".msg-content-image";
				mui(document).on("tap", imgEl, function() {
					var imgs = [];
					var current;
					mui(imgEl).each((i, obj) => {
						imgs.push(obj.getAttribute("src"))
						if (this === obj) {
							current = i;
						}
					})
					plus.nativeUI.previewImage(imgs, {
						current: current,
						indicator: "default",
						loop: false
					})
				})

			})

			function initCurrentPage(webview) {
				const userName = webview._ext_user_name;

				$("#page-title").html("与" + userName + "对话");

				renderMsgHistory();

				plus.nativeUI.closeWaiting();
				plus.webview.currentWebview().show("slide-in-right");

			}

			function renderMsgHistory() {
				const historys = msgHistoryManager.getMsg();

				var html = "";
				if (historys) {
					for (var i = 0; i < historys.length; i++) {
						if (historys[i].type === 0) {
							html+=CHAT.getSysHtml(historys[i].entity);
						} else if (historys[i].type === 1) {
							html+=CHAT.getMeHtml(historys[i].entity);
						} else if (historys[i].type === 2) {
							html+=CHAT.getFriendHtml(historys[i].entity);
						}
					}
					$("#msg-list").html(html);
					CHAT.checkAndScollDown()
				}

			}
		</script>
	</body>

</html>
